/*
 * CustomProgressDialog.java
 * Author:  lixh
 * Create Date:  2015年9月6日
 */
package com.yinhai.view;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.yinhai.activity.R;
import com.yinhai.util.Utils;

/**
 * CustomProgressDialog (<类描述>)
 *
 * Author:lixh
 */
public class CustomProgressDialog extends ProgressDialog {
    private TextView titleView, precentView, totalView;
    
    private ProgressBar progressBar;
    
    private View rootView;
    private Context context;
   
    
    public CustomProgressDialog(Context context, int theme) {
        super(context, theme);
        this.context=context;
    }
    
    public CustomProgressDialog(Context context) {
        super(context);
        this.context=context;
        rootView = LayoutInflater.from(context).inflate(R.layout.custom_progress_dialog, null);
        this.titleView = (TextView)rootView.findViewById(R.id.item_title);
        this.progressBar = (ProgressBar)rootView.findViewById(R.id.item_progress);

        this.precentView = (TextView)rootView.findViewById(R.id.item_percent);
        this.totalView = (TextView)rootView.findViewById(R.id.item_total);
        setMax(100);
        
    }
    
    @Override
    public void setMessage(CharSequence message) {
        super.setMessage(message);
        if (this.titleView != null) {
            this.titleView.setText(message);
        }
    }
    
    @Override
    public void setProgress(int value) {
        super.setProgress(value);
        if (progressBar != null) {
            progressBar.setProgress(value);
            Message message = new Message();
            message.what = 1;
            message.obj = value;
            handler.sendMessage(message);
        }
    }
    
    @Override
    public void setMax(int max) {
        super.setMax(max);
    }
    
    @Override
    public void show() {
        super.show();
        setContentView(rootView);
        DisplayMetrics dm = new DisplayMetrics();
        dm = context.getApplicationContext().getResources().getDisplayMetrics();
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.width = dm.widthPixels-Utils.dip2px(context, 60); // 设置宽度
        getWindow().setAttributes(lp);
    }
    
    private Handler handler = new Handler(new Handler.Callback() {
        
        @Override
        public boolean handleMessage(Message message) {
            if (message.what == 1) {
                if (precentView != null) {
                    precentView.setText(((Integer)(message.obj) * 100 / progressBar.getMax()) + "%");
                }
            }
            return false;
        }
    });
    
}
